package com.lzb.permanentcalendar.fragment;

import android.icu.util.Calendar;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lzb.permanentcalendar.BaseNoModelFragment;
import com.lzb.permanentcalendar.R;
import com.lzb.permanentcalendar.activity.FestivalAssistantActivity;
import com.lzb.permanentcalendar.adapter.HomeFestivalAdapter;
import com.lzb.permanentcalendar.databinding.FragmentHomeBinding;
import com.lzb.permanentcalendar.dialog.SelDateDialog;
import com.lzb.permanentcalendar.utils.DateCalculator;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;
import com.othershe.calendarview.bean.DateBean;
import com.othershe.calendarview.bean.JrBean;
import com.othershe.calendarview.listener.OnPagerChangeListener;
import com.othershe.calendarview.listener.OnSingleChooseListener;
import com.othershe.calendarview.utils.DateUtils;
import com.othershe.calendarview.utils.LunarUtil;
import com.othershe.calendarview.utils.SolarUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> implements View.OnClickListener {

    private HomeFestivalAdapter festivalAdapter;
    private boolean isShowGregorianCalendar = true;
    private SelDateDialog selDateDialog;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mDataBinding.tvGlDate.setOnClickListener(this);
        mDataBinding.rlChange.setOnClickListener(this);
        mDataBinding.ivLastDay.setOnClickListener(this);
        mDataBinding.ivNextDay.setOnClickListener(this);
        mDataBinding.tvAll.setOnClickListener(this);

        mDataBinding.rvFestivalList.setLayoutManager(new LinearLayoutManager(mContext));
        festivalAdapter = new HomeFestivalAdapter();
        mDataBinding.rvFestivalList.setAdapter(festivalAdapter);

        Solar solar = Solar.fromDate(new Date());
        //日历init，年月日之间用点号隔开
        mDataBinding.calendar
                .setStartEndDate("1990.1", "2100.12")
                .setInitDate(solar.getYear() + "." + solar.getMonth())
                .setSingleDate(solar.getYear() + "." + solar.getMonth() + "." + solar.getDay())
                .init();
        setLunar(solar.getYear(), solar.getMonth(), solar.getDay());
        int endNum = DateCalculator.getDaysUntilEndOfYear();
        mDataBinding.tvUntilYearEnd.setText(getString(R.string.until_year_end_text1, solar.getYear()));
        mDataBinding.tvUntilYearEndNum.setText(" " + endNum + " ");
        mDataBinding.tvGlDate.setText(solar.getYear() + "年" + solar.getMonth() + "月" + solar.getDay() + "日");
        //月份切换回调
        mDataBinding.calendar.setOnPagerChangeListener(new OnPagerChangeListener() {
            @Override
            public void onPagerChanged(int[] date) {
                if (date.length > 2) {
                    mDataBinding.tvGlDate.setText(date[0] + "年" + date[1] + "月" + date[2] + "日");
                    mDataBinding.calendar.toSpecifyDate(date[0], date[1], date[2]);
                    setLunar(date[0], date[1], date[2]);
                    mDataBinding.calendar.setSingleDate(date[0] + "." + date[1] + "." + date[2]);
                }
            }
        });
        //单选回调
        mDataBinding.calendar.setOnSingleChooseListener(new OnSingleChooseListener() {
            @Override
            public void onSingleChoose(View view, DateBean date) {
                int[] solar1 = date.getSolar();
                int year = solar1[0];
                int mo = solar1[1];
                int day = solar1[2];
                setLunar(solar1[0], solar1[1], solar1[2]);
                mDataBinding.calendar.setSingleDate(year + "." + mo + "." + day);
                mDataBinding.tvGlDate.setText(solar1[0] + "年" + solar1[1] + "月" + solar1[2] + "日");
                Log.e(TAG, "onSingleChoose: ");
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvGlDate) {//日期
            showSelDateDialog();
        } else if (id == R.id.rlChange) {//切换公历/农历
            isShowGregorianCalendar = !isShowGregorianCalendar;
            mDataBinding.llGregorianCalendar.setVisibility(isShowGregorianCalendar ? View.VISIBLE : View.GONE);
            mDataBinding.llChineseCalender.setVisibility(isShowGregorianCalendar ? View.GONE : View.VISIBLE);
            mDataBinding.tvChange.setText(isShowGregorianCalendar ? getString(R.string.chinese_calendar) : getString(R.string.gregorian_calendar));
        } else if (id == R.id.ivLastDay) {//上一天
            DateBean dateBean = mDataBinding.calendar.getSingleDate();
            Log.e(TAG, "onClick: " + dateBean.getSolar()[0] + "-" + dateBean.getSolar()[1] + "-" + dateBean.getSolar()[2]);
            int[] date = DateCalculator.getPreviousDay(dateBean.getSolar()[0], dateBean.getSolar()[1], dateBean.getSolar()[2]);
            int year = date[0];
            int mo = date[1];
            int day = date[2];
            setLunar(date[0], date[1], date[2]);
            Log.e(TAG, "onClick: " + year + "-" + mo + "-" + day);
            if (mo < dateBean.getSolar()[1]) {
                mDataBinding.calendar.setLastClickDay(day);
                mDataBinding.calendar.lastMonth();
            }
            mDataBinding.calendar.toSpecifyDate(year, mo, day);
            mDataBinding.calendar.setSingleDate(year + "." + mo + "." + day);
            mDataBinding.tvGlDate.setText(date[0] + "年" + date[1] + "月" + date[2] + "日");
        } else if (id == R.id.ivNextDay) {//下一天
            DateBean dateBean = mDataBinding.calendar.getSingleDate();
            int[] date = DateCalculator.getNextDay(dateBean.getSolar()[0], dateBean.getSolar()[1], dateBean.getSolar()[2]);
            int year = date[0];
            int mo = date[1];
            int day = date[2];
            setLunar(date[0], date[1], date[2]);
            if (mo > dateBean.getSolar()[1]) {
                mDataBinding.calendar.setLastClickDay(day);
                mDataBinding.calendar.nextMonth();
            }
            mDataBinding.calendar.toSpecifyDate(year, mo, day);
            mDataBinding.calendar.setSingleDate(year + "." + mo + "." + day);
            mDataBinding.tvGlDate.setText(date[0] + "年" + date[1] + "月" + date[2] + "日");
        } else if (id == R.id.tvAll) {//全部
            startActivity(FestivalAssistantActivity.class);
        }
    }

    @Override
    protected void initData() {

    }

    private void setLunar(int year, int month, int day) {
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.set(year, month - 1, day);
        ; // 注意月份从0开始

        findNextFestivals(selectedDate);
        try {
            // 1. 创建公历对象
            Solar solar = Solar.fromYmd(year, month, day);
            Lunar lunar = solar.getLunar();

            // 2. 基础信息
            String yearGanZhi = lunar.getYearInGanZhi();       // 年干支（乙巳）
            String yearShengXiao = lunar.getYearShengXiao(); // 生肖（蛇）
            String monthGanZhi = lunar.getMonthInGanZhi();    // 月干支（辛巳）
            String dayGanZhi = lunar.getDayInGanZhi();         // 日干支（丁酉）
            String lunarDate = lunar.getMonthInChinese() + "月" + lunar.getDayInChinese(); // 农历五月初二
            int week = selectedDate.get(Calendar.WEEK_OF_YEAR);

            // 3. 神位方位（需根据实际库字段名调整）
            String caiShen = lunar.getDayPositionCaiDesc();      // 财神方位// 财神方位
            String xiShen = lunar.getDayPositionXiDesc();        // 喜神方位
            String fuShen = lunar.getDayPositionFuDesc();        // 福神方位
            String yangGui = lunar.getDayPositionYangGuiDesc();  // 阳贵神方位

            // 4. 宜忌事项
            List<String> yiList = lunar.getDayYi();          // 宜事项列表
            List<String> jiList = lunar.getDayJi();         // 忌事项列表
            String yi = String.join(" ", yiList);
            String ji = String.join(" ", jiList);

            // 5. 格式化输出
            System.out.println("公历日期：" + solar);
            System.out.println("干支信息：" + yearGanZhi + "·" + yearShengXiao + "年 "
                    + monthGanZhi + "月 " + dayGanZhi + "日");
            System.out.println("农历日期：" + lunarDate);
            System.out.println("神位方位：财神 " + caiShen
                    + "，喜神 " + xiShen
                    + "，福神 " + fuShen
                    + "，阳贵 " + yangGui);
            System.out.println("宜：" + yi);
            System.out.println("忌：" + ji);

            mDataBinding.tvNlDate.setText(lunarDate);
            mDataBinding.tvGzDate.setText("第" + week + "周 " + yearGanZhi + "年 "
                    + monthGanZhi + "月 " + dayGanZhi + "日 【属" + yearShengXiao + "】");

            mDataBinding.tvYi.setText(yi);
            mDataBinding.tvJi.setText(ji);
            mDataBinding.tvGzNlDate.setText(yearGanZhi + yearShengXiao + "年" + lunarDate);

            mDataBinding.tvChineseCalenderDate.setText(yearGanZhi + "·" + yearShengXiao + "年 "
                    + monthGanZhi + "月 " + dayGanZhi + "日");
            mDataBinding.tvChineseCalenderDay.setText(lunar.getDayInChinese());
            mDataBinding.tvChineseCalenderMonth.setText(lunar.getMonthInChinese() + "月");
            mDataBinding.tvChineseCalenderWeek.setText(new SimpleDateFormat("EEEE").format(selectedDate.getTime()));

            Solar d = Solar.fromYmd(2025, 5, 12);
            List<String> l = d.getFestivals();
            for (String s : l) {
                System.out.println(s);
            }

            d = Solar.fromYmd(2025, 5, 12);
            l = d.getOtherFestivals();
            for (String s : l) {
                System.out.println(s);
            }
        } catch (Exception e) {
            System.err.println("日期解析错误：" + e.getMessage());
        }
    }

    private void findNextFestivals(Calendar startDate) {
        List<JrBean> festivals = new ArrayList<>();
        Calendar tempDate = (Calendar) startDate.clone();

        // 跳过起始日（用户可能不需要当天）
        while (festivals.size() < 3) {
            if (getFestivalName(tempDate) != null) {
                JrBean festivalName = getFestivalName(tempDate);
                int year = startDate.get(Calendar.YEAR);

                // 获取月份（注意：Calendar 的月份从 0 开始，实际需 +1）
                int month = startDate.get(Calendar.MONTH) + 1;
                // 获取日期（月份中的第几天）
                int day = startDate.get(Calendar.DAY_OF_MONTH);
                int days = (int) DateUtils.calculateDaysBetween(year + "-" + month + "-" + day,
                        festivalName.year + "-" + festivalName.mo + "-" + festivalName.day);
                festivalName.num = days;

                for (int i = 0; i < festivals.size(); i++) {
                    if (festivals.get(i).jrName.contains(festivalName.getJrName())) {
                        festivals.remove(i);
                    }
                }
                festivals.add(festivalName);

            }
            tempDate.add(Calendar.DAY_OF_MONTH, 1);
        }
        festivalAdapter.setList(festivals);
    }

    private JrBean getFestivalName(Calendar date) {
        int month = date.get(Calendar.MONTH) + 1;
        int day = date.get(Calendar.DAY_OF_MONTH);
        if (month == 0) {
            month = month + 1;
        }
        try {
            Solar solar = new Solar(date.get(Calendar.YEAR), month, day);
            // 转阴历
            Lunar lunar = solar.getLunar();
            String lunarHoliday = LunarUtil.getLunarHolidayTxt(lunar.toFullString());
            if (!TextUtils.isEmpty(lunarHoliday)) {
                JrBean jrBean = new JrBean();
                jrBean.setJrName(lunarHoliday);
                jrBean.year = date.get(Calendar.YEAR);
                jrBean.mo = month;
                jrBean.day = day;
                return jrBean;
            }
        } catch (Exception e) {
        }
        try {
            String solarHoliday = SolarUtil.getSolarHoliday(date.get(Calendar.YEAR), month, day);
            if (!TextUtils.isEmpty(solarHoliday)) {
                JrBean jrBean = new JrBean();
                jrBean.setJrName(solarHoliday);
                jrBean.year = date.get(Calendar.YEAR);
                jrBean.mo = month;
                jrBean.day = day;
                return jrBean;
            }
        } catch (Exception e) {

        }

        return null;
    }

    private void showSelDateDialog() {
        if (selDateDialog == null) selDateDialog = new SelDateDialog(mContext);
        selDateDialog.setListener(new SelDateDialog.Ilistener() {
            @Override
            public void clickConfirm(int type, int year, int mo, int days) {
                if (type == 0) {
                    mDataBinding.calendar.toSpecifyDate(year, mo, days);
                    mDataBinding.tvGlDate.setText(year + "年" + mo + "月" + days + "日");
                    setLunar(year, mo, days);
                } else if (type == 1) {
                    Lunar lunar = new Lunar(year, mo, days);
                    // 转换为阳历
                    Solar solar = lunar.getSolar();
                    setLunar(solar.getYear(), solar.getMonth(), solar.getDay());
                    mDataBinding.calendar.toSpecifyDate(solar.getYear(), solar.getMonth(), solar.getDay());
                    mDataBinding.tvGlDate.setText(solar.getYear() + "年" + solar.getMonth() + "月" + solar.getDay() + "日");
                }
            }
        });
        selDateDialog.show();
    }

}